﻿app.controller('GroceryController',
['$scope', '$http', 'GroceryService',
function ($scope, $http, GroceryService) {
    $scope.total = 0;

    $scope.purchaseItem = function (groceryItemId) {
        $scope.isLoading = !$scope.isLoading;
        angular.forEach($scope.groceryList, function (value, key) {
            if (value.groceryItemId === groceryItemId) {
                return GroceryService.purchaseItem(value).then(function () {
                    $scope.isLoading = !$scope.isLoading;
                }, function () {
                    $scope.isLoading = !$scope.isLoading;
                });
            }
        });
    };

    return GroceryService.getGroceryList().then(function (data) {
        //Resolve or 'success'/ok callback
        $scope.isInitialized = $scope.isAuthenticated = true;
        $scope.groceryList = data;
        //for (var i in data) {
        //    $scope.total += (data[i].itemPrice * data[i].quantity);
        //}
    }, function (data) {
        $scope.isInitialized = true;
        $scope.isAuthenticated = false;
        //Reject or error callback
    });
}]);